package com.atguigu.flink.watermark;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import com.atguigu.flink.utils.MyUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

/**
 * Created by Smexy on 2023/2/1
 *
 *      迟到:  当前数据的eventtime  < watermark
 *
 *      处理迟到:
 *                  第一板斧:延迟水印的推进，调慢表
 *                          forBoundedOutOfOrderness(Duration 调慢的程度)
 *
 *                   第二板斧: 延迟窗口关闭的时间。
 *                              到点后就触发窗口的运算，不关闭窗口。
 *                              后续迟到的数据，依旧可以进入窗口，每进入一个，就立刻再触发窗口的运算
 *
 *                   第三板斧: 针对窗口关闭后，依旧迟到的数据，可以使用侧流接收，等待后续处理！
 *
 *              这三种措施都无法解决场景，说明乱序程度太大。只能从源头解决乱序问题，或使用批处理！
 *
 */
public class Demo3_HandleLate
{
    public static void main(String[] args) {

       Configuration conf = new Configuration();
       conf.setInteger("rest.port", 3333);
       StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.getConfig().setAutoWatermarkInterval(2000);

        OutputTag<WaterSensor> lateTag = new OutputTag<>("late", TypeInformation.of(WaterSensor.class));

        //创建水印生成策略
        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
            .withTimestampAssigner((e, ts) -> e.getTs());

        env.setParallelism(1);


        SingleOutputStreamOperator<String> ds = env
            .socketTextStream("hadoop103", 8888)
            .map(new WaterSensorMapFunction())
            .assignTimestampsAndWatermarks(watermarkStrategy)
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            //推迟窗口关闭的时间   4999 + 3000 这个时刻会关闭。 在水印到达7999之前，迟到的数据依旧可以进入窗口，就能触发运算
            .allowedLateness(Time.seconds(3))
            //窗口关闭后，迟到的数据使用侧流输出
            .sideOutputLateData(lateTag)
            /*
                    size = slide = 5s
                    [0,4999] ,[5000,9999]
             */
            .process(new ProcessAllWindowFunction<WaterSensor, String, TimeWindow>()
            {
                @Override
                public void process(Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                    System.out.println(context.window());
                    out.collect(MyUtil.parseList(elements).toString());
                }
            }).startNewChain();

            //主流的数据(未迟到)
        ds.print();
        DataStream<WaterSensor> lateDs = ds.getSideOutput(lateTag);
        lateDs.printToErr();


        try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
